/*
 * network_fifo.c
 *
 *  Created on: 12.07.2012
 *      Author: Jan
 */

#include <string.h>

#include "network.h"
#include "network_private.h"
#include "ecrobot_interface.h"

/*------FIFO------*/
int readpointer = 0, writepointer = 0;
user_msg FIFO[MSG_FIFO_SIZE];

int FIFO_get_fill() //Returns number of messages in FIFO
{
	return (MSG_FIFO_SIZE + writepointer - readpointer) % MSG_FIFO_SIZE;
}

int FIFO_is_empty() //Returns 1 if there is at least one Message in FIFO
{
	return (FIFO_get_fill() == 0) ? 1 : 0;
}

int FIFO_is_full() //Returns 1 if there is no more space in FIFO
{
	return (FIFO_get_fill() == MSG_FIFO_SIZE - 1) ? 1 : 0;
}

void FIFO_write(user_msg* message) {
	if (FIFO_is_full() == 1) {
		readpointer++;
		if (readpointer > MSG_FIFO_SIZE) {
			readpointer = 0;
		}
	}

	FIFO[writepointer++] = *message;
	if (writepointer > MSG_FIFO_SIZE) {
		writepointer = 0;
	}
}

int FIFO_read(user_msg* message) {
	if (FIFO_is_empty() == 0) {
		*message = FIFO[readpointer++];
		if (readpointer > MSG_FIFO_SIZE) {
			readpointer = 0;
		}
		message->msg[DATA_SIZE] = '\0';
		return 1;
	}

	return 0;
}
